package com.skwen.delivery.superdelivery.login;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.databinding.DataBindingUtil;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;

import com.skwen.delivery.superdelivery.BaseActivity;
import com.skwen.delivery.superdelivery.MainActivity;
import com.skwen.delivery.superdelivery.R;
import com.skwen.delivery.superdelivery.databinding.LayoutRegisterEditDialogBinding;
import com.skwen.delivery.superdelivery.databinding.LoginLayoutBinding;
import com.skwen.delivery.superdelivery.login.bean.User;
import com.skwen.delivery.superdelivery.login.loginInterface.UserLoginView;
import com.skwen.delivery.superdelivery.login.loginpresenter.UserLoginPresenter;
import com.skwen.delivery.superdelivery.myGreenDao.manager.UserDBManager;

import java.util.ArrayList;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;


/**
 * Created by yundantian on 2017/8/28.
 * 登录
 */

public class LoginActivity extends BaseActivity implements UserLoginView {

    private LoginLayoutBinding loginLayoutBinding;

    private UserLoginPresenter mUserLoginPresenter;

    private EventHandler eventHandler;

    private Handler handler = new Handler();


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        loginLayoutBinding = DataBindingUtil.setContentView(this, R.layout.login_layout);
        mUserLoginPresenter = new UserLoginPresenter(this);
        addListener();
    }

    private void addListener() {
        loginLayoutBinding.loginLogin.setOnClickListener(v -> {
            mUserLoginPresenter.Login();
        });
        loginLayoutBinding.loginRegister.setOnClickListener(v -> {
            mUserLoginPresenter.openRegister();
        });
        loginLayoutBinding.loginVisitor.setOnClickListener(view -> toMainActivity(null));

        if (Build.VERSION.SDK_INT >= 23) {
            int readPhone = checkSelfPermission(Manifest.permission.READ_PHONE_STATE);
            int receiveSms = checkSelfPermission(Manifest.permission.RECEIVE_SMS);
            int readSms = checkSelfPermission(Manifest.permission.READ_SMS);
            int readContacts = checkSelfPermission(Manifest.permission.READ_CONTACTS);
            int readSdcard = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);

            int requestCode = 0;
            ArrayList<String> permissions = new ArrayList<String>();
            if (readPhone != PackageManager.PERMISSION_GRANTED) {
                requestCode |= 1;
                permissions.add(Manifest.permission.READ_PHONE_STATE);
            }
            if (receiveSms != PackageManager.PERMISSION_GRANTED) {
                requestCode |= 1 << 1;
                permissions.add(Manifest.permission.RECEIVE_SMS);
            }
            if (readSms != PackageManager.PERMISSION_GRANTED) {
                requestCode |= 1 << 2;
                permissions.add(Manifest.permission.READ_SMS);
            }
            if (readContacts != PackageManager.PERMISSION_GRANTED) {
                requestCode |= 1 << 3;
                permissions.add(Manifest.permission.READ_CONTACTS);
            }
            if (readSdcard != PackageManager.PERMISSION_GRANTED) {
                requestCode |= 1 << 4;
                permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            }
            if (requestCode > 0) {
                String[] permission = new String[permissions.size()];
                this.requestPermissions(permissions.toArray(permission), requestCode);
                return;
            }
        }


        // 如果希望在读取通信录的时候提示用户，可以添加下面的代码，并且必须在其他代码调用之前，否则不起作用；如果没这个需求，可以不加这行代码
//        SMSSDK.setAskPermisionOnReadContact(boolShowInDialog)
        // 创建EventHandler对象
        eventHandler = new EventHandler() {

            @Override
            public void afterEvent(int event, int result, Object data) {

                if (result == SMSSDK.RESULT_COMPLETE) {
                    //回调完成
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        //提交验证码成功
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        //获取验证码成功
                        handler.post(() -> {
                            if (registerEditDialogBinding != null) {
                                registerEditDialogBinding.dialogLayoutCancleConfirm.setVisibility(View.VISIBLE);
                                registerEditDialogBinding.dialogLayoutNext.setVisibility(View.GONE);
                                registerEditDialogBinding.dialogEditPassword.setVisibility(View.VISIBLE);
                            }
                        });
                    }
                } else {
                    ((Throwable) data).printStackTrace();
                }
            }
        };
        SMSSDK.registerEventHandler(eventHandler); //注册短信回调

    }

    @Override
    public String getUserName() {
        return loginLayoutBinding.loginAccount.getText().toString();
    }

    @Override
    public String getPassword() {
        return loginLayoutBinding.loginPassword.getText().toString();
    }

    @Override
    public void clearUserName() {
        loginLayoutBinding.loginAccount.setText("");
    }

    @Override
    public void clearPassword() {
        loginLayoutBinding.loginPassword.setText("");
    }

    @Override
    public void showsLoading() {
        showLoading();
    }

    @Override
    public void hideLoading() {
        stopLoading();
    }

    @Override
    public void toMainActivity(User user) {
        saveLoginState(user);
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void showFailedError(String error) {
        loginLayoutBinding.loginAccount.setText("");
        loginLayoutBinding.loginPassword.setText("");
        Snackbar.make(loginLayoutBinding.getRoot(), error, Snackbar.LENGTH_LONG)
                .setAction("Action", null).show();
    }

    @Override
    public void toRegister() {
        showEditDialog();

    }

    @Override
    public void register(User user) {
        toMainActivity(user);
    }


    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterEventHandler(eventHandler);
    }


    private AlertDialog.Builder dialog;
    private AlertDialog alertDialog;
    private LayoutRegisterEditDialogBinding registerEditDialogBinding;

    protected void showEditDialog() {
        dialog = new AlertDialog.Builder(mContext);
//        View view = getLayoutInflater().inflate(R.layout.layout_register_edit_dialog, null);
        registerEditDialogBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.layout_register_edit_dialog, null, false);
        registerEditDialogBinding.dialogLayoutNext.setVisibility(View.VISIBLE);
        registerEditDialogBinding.dialogGetCode.setOnClickListener(v -> {
            if (!TextUtils.isEmpty(registerEditDialogBinding.dialogEdit.getText())) {
                SMSSDK.getVerificationCode("86", registerEditDialogBinding.dialogEdit.getText().toString().trim());
            } else {
                showToast(registerEditDialogBinding.dialogEdit, "请输入手机号");
            }
        });
        registerEditDialogBinding.dialogNext.setOnClickListener(v -> {
            if (!TextUtils.isEmpty(registerEditDialogBinding.dialogEdit.getText()) && !TextUtils.isEmpty(registerEditDialogBinding.dialogGetCode.getText())) {
                SMSSDK.submitVerificationCode("86", registerEditDialogBinding.dialogEdit.getText().toString().trim(), registerEditDialogBinding.dialogGetCode.getText().toString());
            } else {
                showToast(v, "请输入手机号或者验证码");
            }
        });

        registerEditDialogBinding.dialogCancle.setOnClickListener(v -> {
            alertDialog.dismiss();
        });

        registerEditDialogBinding.dialogConfirm.setOnClickListener(v -> {
            if (!TextUtils.isEmpty(registerEditDialogBinding.dialogEditPassword.getText())) {
                User user = new User();
                user.setUserName(registerEditDialogBinding.dialogEdit.getText().toString());
                user.setUserPhone(registerEditDialogBinding.dialogEdit.getText().toString());
                user.setUserAccount(registerEditDialogBinding.dialogEdit.getText().toString());
                user.setUserPsd(registerEditDialogBinding.dialogEditPassword.getText().toString());
                user.setUserSex("未设置");
                alertDialog.dismiss();
                mUserLoginPresenter.register(user);
            } else {
                showToast(v, "请设置密码");
            }
        });
        dialog.setView(registerEditDialogBinding.getRoot());
        dialog.setCancelable(false);
        dialog.setOnKeyListener((DialogInterface dialog, int keyCode, KeyEvent event) -> {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                alertDialog.dismiss();
                return true;
            } else
                return false;
        });
        alertDialog = dialog.show();
    }


    private void saveLoginState(User user) {
        UserDBManager userDbManager = UserDBManager.getInstance(this);
        User list = userDbManager.queryUserList(user.getUserPhone());
        if (list != null) {
            userDbManager.updateUser(user);
        } else
            userDbManager.insertUser(user);
    }


}
